#encoding=utf-8
'''
Created on 2014-1-21

@author: yongbing.chen

'''
import redis

class ConnectRedis():
    def __init__(self,RedisHost,RedisPort,db=0):
        self.pool = redis.ConnectionPool(host=RedisHost, port=RedisPort,db=db) 
    def hgetall(self,name):
        rConnect = redis.Redis(connection_pool=self.pool)  
        return rConnect.hgetall(name)
    
    def flushall(self):
        rConnect = redis.Redis(connection_pool=self.pool)  
        rConnect.flushall()
        
    def hmset(self,name,fieldvals):
        rConnect = redis.Redis(connection_pool=self.pool) 
#         for i in [i*2 for i in range(len(fieldvals)/2)]:
#             field, value = fieldvals[i:i+2]
        rConnect.hmset(name, fieldvals)
        
    def hset(self,name,field,value):
        rConnect = redis.Redis(connection_pool=self.pool) 
        rConnect.hset(name, field, value)
    def hget(self,name,field):
        rConnect = redis.Redis(connection_pool=self.pool) 
        return rConnect.hget(name, field)
    def lset(self,name,index,value):
        rConnect = redis.Redis(connection_pool=self.pool)
        rConnect.lset(name, index, value)
    def lpush(self,name,*vals):
        rConnect = redis.Redis(connection_pool=self.pool)
        rConnect.lpush(name,','.join(vals))
    def exists(self,name):
        rConnect = redis.Redis(connection_pool=self.pool)
        return rConnect.exists(name)
    def keys(self,pattern):
        rConnect = redis.Redis(connection_pool=self.pool)
        return rConnect.keys(pattern)
    def zrange(self,name,start,end):
        rConnect = redis.Redis(connection_pool=self.pool)
        return rConnect.zrange(name,start,end)
    
    
    def zadd(self,name,id,value):
        rConnect = redis.Redis(connection_pool=self.pool)
        return rConnect.zadd(name,value,id)
       
    def delete(self,names):
        rConnect = redis.Redis(connection_pool=self.pool)
        r = []
        i=0
        for name in names:
            i+=rConnect.delete(name)

        return 'delete %s/%s'%(i,len(names))
    def zcard(self,name):
        rConnect = redis.Redis(connection_pool=self.pool)
        return rConnect.zcard(name)
    def hlen(self,name):
        rConnect = redis.Redis(connection_pool=self.pool)
        return rConnect.hlen(name)
    def mset(self,args):
        rConnect = redis.Redis(connection_pool=self.pool)
        rConnect.mset(args)
    def subscribe(self,channels):
        rConnect = redis.Redis(connection_pool=self.pool)
        pub = rConnect.pubsub()
        pub.subscribe(channels)
        while True:
            print "pub sub"
            for data in pub.listen():
                print data['data']
        count = 0
        return count
if __name__=='__main__':
    ConnectRedis = ConnectRedis('172.20.1.71',6379)
    #print ConnectRedis.delete(['src_2014-02-27.1000000004.[52:54:00:a4:23:2b]'])
    print ConnectRedis.subscribe('ii_ch')
    